package com.mrzhou.web.feign;

import com.mrzhou.core.tool.api.R;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 *
 * @param <T>
 */
@Slf4j
public class CloudFeignFallback<T> implements MethodInterceptor {

    private final Class<T> targetType;

    private final String targetName;

    private final Throwable throwable;

    public CloudFeignFallback(Class<T> targetType, String targetName, Throwable throwable) {
        this.targetType = targetType;
        this.targetName = targetName;
        this.throwable = throwable;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String errorMessage = throwable.getMessage();
        log.error("CloudFeignFallback:[{}.{}] serviceId: [{}] message: [{}]", targetType.getName(), method.getName(), targetName, errorMessage);
        // 非FeignException, 直接返回
        if(!(throwable instanceof FeignException)) {
            // TODO 确认何种情况下会处理
            return R.fail(errorMessage);
        }

        FeignException exception = (FeignException) throwable;
        return R.fail(exception.getMessage());
    }
}
